package com.mibox.common.ui;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ResourceUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.mibox.common.R;
import com.mibox.common.adapter.AppGridAdapter;
import com.mibox.common.app.AppDataManage;
import com.mibox.common.app.AppEntry;
import com.mibox.common.consts.MMKVKey;
import com.mibox.common.databinding.ActivityMainBinding;
import com.mibox.common.event.PackageEvent;
import com.mibox.common.utils.HttpHelper;
import com.mibox.common.utils.ticker.AppTicker;
import com.mibox.common.utils.ticker.TickCallback;
import com.tencent.mmkv.MMKV;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;


public class MainActivity extends Activity
        implements OnItemClickListener, OnItemLongClickListener, TickCallback {

    private ActivityMainBinding mB;
    private AppGridAdapter mAppAdapter;
    private AppDataManage mAppListManager;
    private String mAppPackage = null;
    private int mDisplaySeconds = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        long count = MMKV.defaultMMKV().getLong(MMKVKey.KEY_MAIN_COUNT, 0) + 1;
        MMKV.defaultMMKV().putLong(MMKVKey.KEY_MAIN_COUNT, count);
        ToastUtils.showLong("App Start: " + count);
        HttpHelper.INSTANCE.init();
        mB = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mB.getRoot());
        mAppPackage = AppUtils.getAppPackageName();
        mAppListManager = new AppDataManage(this);
        mB.appList.setLayoutManager(new GridLayoutManager(this, 4));
        initAppListAdapter();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onGetMessage(PackageEvent e) {
        loadAppList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.d("On Home Resume!");
        mDisplaySeconds = 0;
        AppTicker.INSTANCE.register(this);
        loadAppList();
    }

    @Override
    protected void onPause() {
        mDisplaySeconds = 0;
        AppTicker.INSTANCE.unregister(this);
        super.onPause();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mDisplaySeconds = 0;
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        mDisplaySeconds = 0;
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSecondTick(long sec) {
        mDisplaySeconds += 1;
        if (mDisplaySeconds >= 60) {
            ActivityUtils.startActivity(SleepClockActivity.class);
        }
    }

    @Override
    public void onBackPressed() {
        mDisplaySeconds = 0;
        ActivityUtils.startActivity(ClockActivity.class);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    private void initAppListAdapter() {
        mAppAdapter = new AppGridAdapter();
        mAppAdapter.setAnimationEnable(true);
        mAppAdapter.addHeaderView(inflateListHeader());
        mAppAdapter.addFooterView(inflateListHeader());
        mB.appList.setAdapter(mAppAdapter);
        mAppAdapter.setOnItemClickListener(this);
        mAppAdapter.setOnItemLongClickListener(this);
    }

    private View inflateListHeader() {
        return getLayoutInflater().inflate(R.layout.layut_grid_space, mB.appList, false);
    }

    private void loadAppList() {
        ArrayList<AppEntry> appList = mAppListManager.getLaunchAppList();
        appList.add(0, getFakeEntry(getString(R.string.more_settings), ConfigActivity.class.getName(), R.drawable.ic_more_settings));
        mAppAdapter.setList(appList);
    }

    private AppEntry getFakeEntry(String label, String name, @DrawableRes int icon) {
        AppEntry entry = new AppEntry();
        entry.isFake = true;
        entry.icon = ResourceUtils.getDrawable(icon);
        entry.label = label;
        entry.launcherName = name;
        return entry;
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        AppEntry it = (AppEntry) adapter.getItem(position);
        if (it.isFake) {
            ActivityUtils.startActivity(this, getPackageName(), it.launcherName);
        } else if (mAppPackage.equals(it.packageName)) {
            ToastUtils.showLong("我正在运行!");
        } else {
            AppUtils.launchApp(it.packageName);
        }
    }

    @Override
    public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        AppEntry it = (AppEntry) adapter.getItem(position);
        if (!it.isFake) {
            AppUtils.launchAppDetailsSettings(it.packageName);
        }
        return true;
    }
}
